package demo.base.service;

import java.sql.Blob;
import java.sql.Timestamp;

import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.Transaction;

import tools.HibernateBlobUtil;
import demo.base.bean.*;
import demo.base.dao.*;

/** 
 * 变成可以序列化的对象
 * 日志记录 content 可序列化的对象
 * 
 * @author Administrator
 * 
 */

public class TLogService {

	// 单例模式 start
	private volatile static TLogService instance = null;
	private TLogDao tLogDao;

	private TLogService() {
		tLogDao = (TLogDao) _BaseDao.ac.getBean("TLogDao");

	}

	public static TLogService getInstance() {
		if (instance == null) {
			synchronized (TLogService.class) {// 1
				if (instance == null) {// 2
					instance = new TLogService();// 3
				}
			}
		}
		return instance;
	}

	// 单例模式 end

	public boolean saveLog(Integer creator, Blob content) {
		Session session = null;
		try {
			TLog log = new TLog(content, creator, new Timestamp(
					System.currentTimeMillis()));
			// Transaction begin
			String sql = null;
			SQLQuery query = null;

			Transaction tx = null;
			session = this.tLogDao.getSessionFactory().getCurrentSession();
			tx = session.beginTransaction();

			session.save(log);

			tx.commit();
			return true;
		} catch (Exception e) {
			return false;
		} finally {
			if (session.isOpen())
				session.close();
		}
	}

	public Object getLog(Integer id) {
		TLog w = this.tLogDao.findByHql("from TLog where id =" + id).get(0);
		return HibernateBlobUtil.BlobToObject(w.getContent()); // 序列化对象 取 记得转型
	}

	public TLogDao gettLogDao() {
		return tLogDao;
	}

}
